import { MigrationInterface, QueryRunner } from 'typeorm';

export class FixActivityParticipantsTable1625000000004 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // 检查表是否存在
    const tableExists = await queryRunner.hasTable('activity_participants');
    if (!tableExists) {
      console.log('activity_participants 表不存在，创建新表');
      
      await queryRunner.query(`
        CREATE TABLE activity_participants (
          id INT AUTO_INCREMENT PRIMARY KEY,
          userId INT NOT NULL,
          activityId INT NOT NULL,
          hasCheckedIn BOOLEAN DEFAULT false,
          checkinTime DATETIME NULL,
          joinTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
          updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE,
          FOREIGN KEY (activityId) REFERENCES activities(id) ON DELETE CASCADE
        )
      `);
      
      return;
    }

    // 检查列是否存在，如果不存在则添加
    const hasUserId = await queryRunner.hasColumn('activity_participants', 'userId');
    if (!hasUserId) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN userId INT NOT NULL
      `);
    }

    // 检查是否存在 user_id 列（可能是旧的命名方式）
    const hasUserIdOld = await queryRunner.hasColumn('activity_participants', 'user_id');
    if (hasUserIdOld && hasUserId) {
      // 如果同时存在 user_id 和 userId，将 user_id 的值复制到 userId
      await queryRunner.query(`
        UPDATE activity_participants SET userId = user_id WHERE userId = 0
      `);
      
      // 不要尝试删除 user_id 列，因为这可能导致错误
      console.log('已将 user_id 列的值复制到 userId 列');
    }

    // 检查 activityId 列是否存在
    const hasActivityId = await queryRunner.hasColumn('activity_participants', 'activityId');
    if (!hasActivityId) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN activityId INT NOT NULL
      `);
    }

    // 检查是否存在 activity_id 列（可能是旧的命名方式）
    const hasActivityIdOld = await queryRunner.hasColumn('activity_participants', 'activity_id');
    if (hasActivityIdOld && hasActivityId) {
      // 如果同时存在 activity_id 和 activityId，将 activity_id 的值复制到 activityId
      await queryRunner.query(`
        UPDATE activity_participants SET activityId = activity_id WHERE activityId = 0
      `);
      
      // 不要尝试删除 activity_id 列，因为这可能导致错误
      console.log('已将 activity_id 列的值复制到 activityId 列');
    }

    // 检查其他必要的列是否存在
    const hasCheckedIn = await queryRunner.hasColumn('activity_participants', 'hasCheckedIn');
    if (!hasCheckedIn) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN hasCheckedIn BOOLEAN DEFAULT false
      `);
    }

    const hasCheckinTime = await queryRunner.hasColumn('activity_participants', 'checkinTime');
    if (!hasCheckinTime) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN checkinTime DATETIME NULL
      `);
    }

    const hasJoinTime = await queryRunner.hasColumn('activity_participants', 'joinTime');
    if (!hasJoinTime) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN joinTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      `);
    }

    const hasUpdatedAt = await queryRunner.hasColumn('activity_participants', 'updatedAt');
    if (!hasUpdatedAt) {
      await queryRunner.query(`
        ALTER TABLE activity_participants ADD COLUMN updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      `);
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 不执行任何回滚操作，避免删除列的问题
    console.log('此迁移不支持回滚操作');
  }
}